package com.lxg.service;

import com.lxg.dao.UserDao;
import com.lxg.pojo.Role;
import com.lxg.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 陆小根
 * date: 2022/04/24
 * Description:
 */
@Service
public class MyUserDetailsService implements UserDetailsService {


  private final UserDao userDao;

  @Autowired
  public MyUserDetailsService(UserDao userDao) {
    this.userDao = userDao;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 1.根据用户名查询用户
    User user = userDao.loadUserByUsername(username);
    if (ObjectUtils.isEmpty(user)) throw new UsernameNotFoundException("用户名不存在");
    // 2.获取角色
    List<Role> roles = userDao.getRolesByUid(user.getId());
    user.setRoles(roles);
    return user;
  }
}
